package com.inventive.system.monitoring.gwt.server.service.statistics;

import com.google.gson.Gson;
import com.inventive.system.monitoring.gwt.client.User;
import com.inventive.system.monitoring.gwt.client.statistics.dto.Chart;
import com.inventive.system.monitoring.gwt.client.statistics.commands.SaveChartAction;
import com.inventive.system.monitoring.gwt.client.statistics.commands.SaveChartResult;
import com.inventive.system.monitoring.server.entity.ChartEntity;
import com.inventive.system.monitoring.server.entity.UserEntity;
import com.inventive.system.monitoring.gwt.server.service.action.ActionHandler;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * User: grant
 */
@Service
public class SaveChartActionHandler implements ActionHandler<SaveChartAction, SaveChartResult> {

    @PersistenceContext
    private EntityManager entityManager;

    private Gson gson = new Gson();

    public SaveChartActionHandler() {
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public SaveChartResult execute(SaveChartAction action) {

        ChartEntity entity = toChartEntity(action.getChart());

        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        User user = (User)attr.getRequest().getSession().getAttribute("user");
        if (user == null) {
            throw new IllegalStateException("User not logged in");
        }

        UserEntity userEntity = entityManager.find(UserEntity.class, user.getUsername());

        entity.setUser(userEntity);


        entity = entityManager.merge(entity);
        entityManager.flush();

        Chart result = toChart(entity);

        return new SaveChartResult(result);
    }

    private ChartEntity toChartEntity(Chart in) {
        ChartEntity out = new ChartEntity();
        out.setId(in.getId());
        out.setJson(gson.toJson(in));
        return out;
    }

    private Chart toChart(ChartEntity in) {
        Chart chart = gson.fromJson(in.getJson(), Chart.class);
        chart.setId( in.getId());
        return chart;
    }

    @Override
    public Class<SaveChartAction> getActionType() {
        return SaveChartAction.class;
    }
}
